package OnlineExam.question;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.sql.*;
import java.util.*;
import OnlineExam.configuration.*;
import static OnlineExam.configuration.Configure.*;


/**
 *  Responsible for generating Question Numbers in a particular series.
 */


public class SimpleQuestionNumberGenerator
{
		
	/**
	 *  Generates numbers in a simple series , returns only those generated numbers which have a 
	 *  corresponding question in the database.
	 */	
	
		
	public static int[] generateQuestionNumbers (String categoryId)throws SQLException, IOException
	{
		Connection connection = null;
		int[] allNumbers = null;

		try
		{
			connection = DriverManager.getConnection (url, username, password);
			Statement statement = connection.createStatement();
		
			String query = "select max(Number) from QuestionBank";
			String query2 = "select TestLength from Category where CategoryId= '" + categoryId + "'" ;
			ResultSet resultSet = statement.executeQuery(query);
			
			int numb = 0, length = 0, count = 0;
		
			if (resultSet.next())
			{
				numb = resultSet.getInt ("max(Number)");	
			}
		
			ResultSet rSet = statement.executeQuery(query2);
		
			if (rSet.next())
			{
				length = rSet.getInt ("TestLength");	
			}
			
			allNumbers = new int[length];
		
			for (int i = 0; i < numb; i++)
			{
				if (questionExists(connection, i, categoryId))
				{
					allNumbers[count++] = i;
					if (count == length)
						return allNumbers;	
				}
			}
			return allNumbers;
		}
		
		catch(SQLException sqle)
		{
			System.out.println ("SQLException " + sqle);
			return allNumbers;
		}
		
		finally
		{
			try { if (connection != null) connection.close();}
			catch (SQLException sqle) { System.out.println ("SQLException " + sqle); }
		}
		
	}

	

	/**
	 *  For a random number generated, it checks if there exists a question in the database.
	 */


	private static boolean questionExists (Connection connection, int qnumber, 
					String categoryId) throws SQLException, IOException
	{	
		
		Statement statement = connection.createStatement ();
		
		String query = "select Number, Question from QuestionBank where CategoryId = '" + categoryId + 
						" ' and  Number = '"+qnumber+"'";
		ResultSet resultSet = statement.executeQuery (query);

		if (resultSet.next())
			return true;
		else
			return false;
	}	
}
